package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     *根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> queryEmployeeById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if(employee!=null) {
            return R.success(employee);
        }
        return R.error("查询失败~");
    }

/*
    编辑用户启用禁用
*/
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("请求携带的数据：{}",employee.toString());
/*        //获取在缓冲中的登录的用户的id
        Long id = (Long) request.getSession().getAttribute("employee");
        //修改修改时间
        employee.setUpdateTime(LocalDateTime.now());
        //设置更新人的id
        employee.setUpdateUser(id);*/
        employeeService.updateById(employee);
        return R.success("修改成功~");
    }

    /*
        分页查询用户信息
    */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        log.info("第几页：{},每页显示条数：{},条件：{}", page, pageSize, name);
        //创建分页对象
        Page<Employee> employeePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //条件查询，如果什么都不查则查询全部
        if (name != null) {
            wrapper.like(Employee::getName, name);
        }
        //方法
        employeeService.page(employeePage, wrapper);
        log.info("查询结果：{}", employeePage);
        return R.success(employeePage);
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        System.out.println("-------------------------");
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);
        System.out.println("-------------------------");
        log.info("新增员工，员工信息：{}", employee.toString());

        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
/*        //设置创建时间
        employee.setCreateTime(LocalDateTime.now());
        //设置修改时间
        employee.setUpdateTime(LocalDateTime.now());

        //获得当前登录用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");
        //通过登录用户的id设置创建人
        employee.setCreateUser(empId);
        //通过登录用户的id设置修改人
        employee.setUpdateUser(empId);*/
        //调用service层方法，保存新增员工
        employeeService.save(employee);
        return R.success("新增员工成功");
    }


    /*
        退出
    */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return R.success("退出成功");

    }

    /*
        登录
    */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        System.err.println(employee);
        //获取密码
        String password = employee.getPassword();
        //通过工具类DigestUtils进行密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        //输出
        log.info(password);
        //
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee result = employeeService.getOne(lambdaQueryWrapper);
        if (result == null) {
            return R.error("查无此用户！");
        }
        if (!result.getPassword().equals(password)) {
            return R.error("密码错误！");
        }
        if (result.getStatus() == 0) {
            return R.error("账号已被禁用");
        }
        //登录成功，将员工id存入session并返回登录结果
        request.getSession().setAttribute("employee", result.getId());
        return R.success(result);
    }


}
